package com.movitech.mobile.cz.base.sys.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.common.util.IdGenUtils;
import com.movitech.mobile.cz.base.common.utils.StringUtils;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.sys.bizvo.DictRequestVO;
import com.movitech.mobile.cz.base.sys.bizvo.DictResponse;
import com.movitech.mobile.cz.base.sys.bizvo.DictResponseVO;
import com.movitech.mobile.cz.base.sys.entity.SysDict;
import com.movitech.mobile.cz.base.sys.mapper.SysDictMapper;
import com.movitech.mobile.cz.base.sys.service.SysDictService;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Movitech Mobile
 * @since 2018-02-28
 */
@Service("sysDictService")
@Transactional
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {

	@Autowired
	private SysDictMapper sysDictMapper;

	@Override
	public RestReturnResult<Object> getDictListByDictType(String dictType,Integer resultType,String parentId) throws Exception {
		RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

//		if(StringUtils.isNotEmpty(dictType)){
			if(resultType!=null&&resultType==1){//返回值dictValue int类型
				List<DictResponseVO> lstDictResponseVO = new ArrayList<DictResponseVO>();
//				Map<String, Object> map = new HashMap<String, Object>();
//				map.put("dict_type", dictType);
//				map.put("del_flag", CommonConstants.NO_INTEGER);
//				List<SysDict> lstSysDict = baseMapper.selectByMap(map);
				EntityWrapper wrapper = new EntityWrapper<>();
				SysDict sysDictObj=new SysDict();
				sysDictObj.setDelFlag(CommonConstants.NO_INTEGER);
				sysDictObj.setDictType(dictType);
				if(StringUtils.isNotBlank(parentId)){
					sysDictObj.setParentId(parentId);
				}
				wrapper.setEntity(sysDictObj);
				wrapper.orderBy("dict_sort");
				List<SysDict> lstSysDict=baseMapper.selectList(wrapper);
				if(!CollectionUtils.isEmpty(lstSysDict)){
					for (SysDict sysDict : lstSysDict) {
						DictResponseVO dictResponseVo = new DictResponseVO();
						BeanUtils.copyProperties(dictResponseVo, sysDict);
						dictResponseVo.setDictValue(Integer.valueOf(sysDict.getDictValue()));
						lstDictResponseVO.add(dictResponseVo);
					}
				}
				hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, lstDictResponseVO);
			}else{//dictValue string 类型
				List<DictResponse> lstDictResponse = new ArrayList<DictResponse>();
//				Map<String, Object> map = new HashMap<String, Object>();
//				map.put("dict_type", dictType);
//				map.put("del_flag", CommonConstants.NO_INTEGER);
				EntityWrapper wrapper = new EntityWrapper<>();
				SysDict sysDictObj=new SysDict();
				sysDictObj.setDelFlag(CommonConstants.NO_INTEGER);
				sysDictObj.setDictType(dictType);
				if(StringUtils.isNotBlank(parentId)){
					sysDictObj.setParentId(parentId);
				}
				wrapper.setEntity(sysDictObj);
				wrapper.orderBy("dict_sort");
				List<SysDict> lstSysDict=baseMapper.selectList(wrapper);
//				List<SysDict> lstSysDict = baseMapper.selectByMap(map);
				if(!CollectionUtils.isEmpty(lstSysDict)){
					for (SysDict sysDict : lstSysDict) {
						DictResponse dictResponseVo = new DictResponse();
						BeanUtils.copyProperties(dictResponseVo, sysDict);
						lstDictResponse.add(dictResponseVo);
					}
				}
				hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, lstDictResponse);
			}
//		}

		return hResult;
	}

	@Override
	public RestReturnResult<Object> saveOrUpdateDict(DictRequestVO reqVO) {
		RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

		SysDict sysDict = null;
		if(reqVO != null){
			if(StringUtils.isNotEmpty(reqVO.getId())){ //update

				sysDict = baseMapper.selectById(reqVO.getId());
				if(sysDict != null){
					sysDict.setDictValue(reqVO.getDictValue());
					sysDict.setDictLabel(reqVO.getDictLabel());
					sysDict.setDictType(reqVO.getDictType());
					sysDict.setDictDescription(reqVO.getDictDescription());
					sysDict.setDictSort(reqVO.getDictSort());
					sysDict.setParentId(reqVO.getParentId());

					Date updateDate = new Date();
					String userId = UserUtils.getCurrentUserId();
					sysDict.setUpdateBy(userId);
					sysDict.setUpdateDate(updateDate);
					sysDict.setDelFlag(CommonConstants.NO_INTEGER);

					baseMapper.updateById(sysDict);

					hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[1], CommonConstants.SUCCESS_DESCS[1]);
				}else{ //数据不存在
					hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
				}

			}else{  //insert

				sysDict = new SysDict();
				sysDict.setId(IdGenUtils.uuid());
				sysDict.setDictValue(reqVO.getDictValue());
				sysDict.setDictLabel(reqVO.getDictLabel());
				sysDict.setDictType(reqVO.getDictType());
				sysDict.setDictDescription(reqVO.getDictDescription());
				sysDict.setDictSort(reqVO.getDictSort());
				sysDict.setParentId(reqVO.getParentId());

				Date createDate = new Date();
				String userId = UserUtils.getCurrentUserId();
				sysDict.setCreateBy(userId);
				sysDict.setCreateDate(createDate);
				sysDict.setUpdateBy(userId);
				sysDict.setUpdateDate(createDate);
				sysDict.setDelFlag(CommonConstants.NO_INTEGER);

				baseMapper.insert(sysDict);

				hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[0], CommonConstants.SUCCESS_DESCS[0]);
			}
		}

		return hResult;
	}

	@Override
	public RestReturnResult<Object> updateDictForDel(String id) {
		RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

		if(StringUtils.isNotEmpty(id)){

			SysDict sysDict = baseMapper.selectById(id);
			if(sysDict != null){
				sysDict.setDelFlag(CommonConstants.YES_INTEGER);

				Date updateDate = new Date();
				String userId = UserUtils.getCurrentUserId();
				sysDict.setUpdateBy(userId);
				sysDict.setUpdateDate(updateDate);

				baseMapper.updateById(sysDict);
			}else{ //数据不存在
				hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
			}

			hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[2], CommonConstants.SUCCESS_DESCS[2]);
		}else{
			hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[3], CommonConstants.ERROR_DESCS[3]);
		}

		return hResult;
	}

    @Override
    public List<SysDict> getSysDictByCode(String code) {
		List<SysDict> sysDicts = new ArrayList<>();
		String[] values = null;
		if("supplier_status_unqualified".equals(code)){//不合格列表的状态
			values = CommonConstants.SUPPLIER_STATUS_UNQUALIFIED.split(",");
		}else if("supplier_status_qualified".equals(code)){//合格列表的状态
			values = CommonConstants.SUPPLIER_STATUS_QUALIFIED.split(",");
		}else if("supplier_status_to_view".equals(code)){//待观察列表的状态
			values = CommonConstants.SUPPLIER_STATUS_TO_VIEW.split(",");
		}else if("supplier_status_black".equals(code)){//黑裤列表的状态
			values = CommonConstants.SUPPLIER_STATUS_BLACK.split(",");
		}else {//supplier_status_potential:潜在列表的状态
			values = CommonConstants.SUPPLIER_STATUS_POTENTIAL.split(",");
		}
		if(values != null){
			Map<String,String> dictMap = new HashMap<>();
			List<SysDict> dicts = sysDictMapper.getDictListByDictType("supplier_status");
			if(dicts != null){
				for(SysDict dict : dicts){
					dictMap.put(dict.getDictValue(), dict.getDictLabel());
				}
			}
			for(String value : values){
				SysDict dict = new SysDict();
				dict.setDictValue(value);
				dict.setDictLabel(dictMap.get(value));
				dict.setDictDescription(dictMap.get(value));
				sysDicts.add(dict);
			}
		}
        return sysDicts;
    }

    /**
     * 根据label和类型，获取字典对象
     * @param dictLabel
     * @param dictType
     * @return
     */
    public SysDict getSysDictByLabelAndType(String dictLabel,String dictType) {
    	SysDict sysDict = new SysDict();
    	sysDict.setDictLabel(dictLabel);
    	sysDict.setDictType(dictType);
    	return sysDictMapper.selectOne(sysDict);
    }

    /**
     * 根据value和类型，获取字典对象
     * @param dictValue
     * @param dictType
     * @return
     */
    public SysDict getSysDictByValueAndType(String dictValue,String dictType) {
    	SysDict sysDict = new SysDict();
    	sysDict.setDictValue(dictValue);
    	sysDict.setDictType(dictType);
    	return sysDictMapper.selectOne(sysDict);
    }

	@Override
	public Map<String, Object> selectMapByType(String type) {
    	Map<String,Object> map = new HashMap<>();
    	EntityWrapper entityWrapper = new EntityWrapper();
		SysDict sysDict = new SysDict();
		sysDict.setDictType(type);
		sysDict.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
		entityWrapper.setEntity(sysDict);
		List<SysDict> list = selectList(entityWrapper);
		for(SysDict sysDict1:list){
			map.put(sysDict1.getDictValue(),sysDict1.getDictLabel());
		}
		return map;
	}
}
